package tuling.netty.quickstart;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @author RenGaoshuai
 * @date 2023/11/30 9:39
 * @description
 * 要求实现：
 * 1.客户端主动连接到服务端后发送消息
 * 2.服务端接收到消息要把消息打印出来
 * 3.服务端要给客户端发送消息
 * 4.客户端接收到消息要把消息打印出来
 */
public class QuickStartClient {

    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();

        try {

            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new QuickStartClientHandler());
                        }
                    });

            System.out.println("QuickStart client start success");

            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9000).sync();

            cf.channel().closeFuture().sync();


        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("QuickStart server interrupted exception");
        } finally {

            group.shutdownGracefully();
        }

    }
}
